import request from '../request'
import { API_ENDPOINTS } from '../config'
import type { Project, ProjectStatus, Stats, ProjectItem } from '../../types'

// 项目列表查询参数
export interface ProjectListParams {
  page?: number
  per_page?: number
  vika_status?: ProjectStatus | 'all'
  customer_name?: string
  manager?: string
  startDate?: string
  endDate?: string
  overdue?: string
}

// 项目创建/更新参数
export interface ProjectFormData {
  [key: string]: any
}

// API响应数据结构 - 简化版本
export interface ApiProjectResponse {
  total: number
  page: number
  per_page: number
  items: Array<{
    project_code: string
    customer_name: string
    customer_domain: string
    project_type: string
    status: ProjectStatus
    vika_status: ProjectStatus
    contract_terms: {
      img?: string | null
      text?: string
      extra_note?: string
      amount?: number
    }
    start_date: string | null
    end_date: string | null
    customer_manager: string | null
    id: number
    created_time: string
    updated_time: string
    contract_requirements: Array<{
      project_id: number
      requirement_type: string
      target_quantity: number
      quality_requirements: {
        as?: number | null
        da?: number | null
        count?: number | null
        dofollow?: boolean | null
      }
      additional_notes: string
      status: 'PENDING' | 'COMPLETED'
      id: number
      created_time: string
      updated_time: string
    }>
  }>
}

// 数据转换函数 - 简化版本
const transformApiDataToProjects = (apiData: ApiProjectResponse): { list: Project[], total: number, page: number, per_page: number } => {
  const projects: Project[] = apiData.items.map(item => {
    // 将合同需求转换为项目条目
    const items: ProjectItem[] = item.contract_requirements.map(req => ({
      id: req.id,
      name: req.requirement_type,
      quantity: req.target_quantity,
      price: 0, // API中没有价格信息，暂时设为0
      details: {
        as: req.quality_requirements?.as || null,
        da: req.quality_requirements?.da || null,
        count: req.quality_requirements?.count || null,
        dofollow: req.quality_requirements?.dofollow || null
      },
      status: req.status
    }))

    // 获取合同金额
    const contractAmount = item.contract_terms.amount

    return {
      id: item.id,
      project_code: item.project_code,
      customer_name: item.customer_name,
      customer_domain: item.customer_domain,
      project_type: item.project_type,
      status: item.status,
      vika_status: item.vika_status,
      contract_terms: item.contract_terms,
      start_date: item.start_date,
      end_date: item.end_date,
      customer_manager: item.customer_manager,
      created_time: item.created_time,
      updated_time: item.updated_time,
      contract_requirements: item.contract_requirements,
      contract_amount: contractAmount,
      contract_count: item.contract_requirements.length,
      items: items
    }
  })

  return {
    list: projects,
    total: apiData.total,
    page: apiData.page,
    per_page: apiData.per_page
  }
}

// 项目 API 服务
export const projectsApi = {
  // 获取项目列表
  async getList(params?: ProjectListParams) {
    const response = await request.get<ApiProjectResponse>(API_ENDPOINTS.PROJECTS.LIST, params)
    const transformedData = transformApiDataToProjects(response.data)
    
    return {
      ...response,
      data: transformedData
    }
  },

  // 获取项目详情
  getDetail(id: number) {
    const url = API_ENDPOINTS.PROJECTS.DETAIL.replace(':id', id.toString())
    return request.get<Project>(url)
  },

  // 创建项目
  create(data: ProjectFormData) {
    return request.post<Project>(API_ENDPOINTS.PROJECTS.CREATE, data)
  },

  // 更新项目
  update(id: number, data: Partial<ProjectFormData>) {
    const url = API_ENDPOINTS.PROJECTS.UPDATE.replace(':id', id.toString())
    return request.put<Project>(url, data)
  },

  // 删除项目
  delete(id: number) {
    const url = API_ENDPOINTS.PROJECTS.DELETE.replace(':id', id.toString())
    return request.delete(url)
  },

  // 获取项目统计
  getStats() {
    return request.get<Stats>(API_ENDPOINTS.PROJECTS.STATS)
  },

  // 获取项目数据统计
  getData() {
    return request.get<{
      total_count: number
      in_progress_count: number
      completed_count: number
      pending_count: number
    }>(API_ENDPOINTS.PROJECTS.DATA)
  },

  // 批量删除项目
  batchDelete(ids: number[]) {
    return request.post('/projects/batch-delete', { ids })
  },

  // 导出项目数据
  export(params?: ProjectListParams) {
    return request.download('/projects/export', 'projects.xlsx', { params })
  },

  // 导入项目数据
  import(file: File) {
    return request.upload('/projects/import', file)
  },
}